import cv2 as cv
cap = cv.VideoCapture(r'vtest.avi')
fgbg = cv.createBackgroundSubtractorMOG2()
thresh = 200 #指定的面积阈值


COLOR=[(255,0,0),(0,255,0),(0,0,255),(254,67,101),(252,157,154),(249,205,173),(131,175,155),(244,208,0),(220,87,18),(138,151,123)]


while True:
    ret, frame = cap.read()
    if not ret:
        break
    fgmask = fgbg.apply(frame)
    _, fgmask = cv.threshold(fgmask, 30, 0xff, cv.THRESH_BINARY)
    bgImage = fgbg.getBackgroundImage()


    _,cnts,_ = cv.findContours(fgmask.copy(),cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
    i=0
    count = 0
    for c in cnts:
        area = cv.contourArea(c)
        if area < thresh:
            continue
        count +=1
        i+=1
        x,y,w,h = cv.boundingRect(c)
        cv.rectangle(fgmask, (x, y), (x + w, y + h), (0,0xff,0), 2)

        cv.rectangle(frame,(x,y),(x+w,y+h),COLOR[i],2)
        print('第',i,'个目标，位置(',x,',',y,') 面积：',area)
        text=str(i)
        cv.putText(frame,text,(x,y+40),cv.FONT_HERSHEY_PLAIN,2,(255,255,255))

    print('共监测到',count,"个目标",'\n')

    cv.imshow('frame', frame)
    cv.imshow('Frontground', fgmask)
    cv.imshow('Background', bgImage)

    key = cv.waitKey(30)#每一帧间隔30ms
    if key == 27: #Esc的ASCII码
        break


cap.release()
cv.destroyAllWindows()
